package service

import (
	"errors"
	"fmt"
	"go-project/common"
	"go-project/dto/requrest"
	"go-project/models"
)

type Permissions struct {
}

func (Permissions) FindList(name string) (lists []models.Permissions, count int64, err error) {
	var permissions *models.Permissions
	query := common.DB.Table(permissions.TableName())
	if len(name) > 0 {
		query = query.Where("display_name like ?", fmt.Sprintf("%%%s%%", name))
	}
	err = query.Model(permissions).Select("count(id)").Count(&count).Error
	err = query.Order("id desc").Find(&lists).Error
	return
}
func (Permissions) Add(request *requrest.PermissionsInsertRequest) (uint, error) {
	var model models.Permissions
	request.Generate(&model)
	result := common.DB.Save(&model)
	return model.ID, result.Error
}

func (Permissions) GetById(id uint) (models.Permissions, error) {
	var model models.Permissions
	result := common.DB.First(&model, id)
	return model, result.Error
}

func (Permissions) Update(request *requrest.PermissionsUpdateRequest) (uint, error) {
	var model models.Permissions
	row := common.DB.First(&model, request.ID)
	if row.Error != nil {
		return 0, row.Error
	}
	request.Generate(&model)
	result := common.DB.Save(&model)
	return model.ID, result.Error

}

func (Permissions) Del(id uint) (uint, error) {
	var model models.Permissions
	first := common.DB.Where("parent_id=?", id).First(&model)
	if !first.RecordNotFound() {
		return 0, errors.New("有下级权限在使用无法删除，请先删除下级")
	}
	result := common.DB.Delete(&model, id)
	return uint(result.RowsAffected), result.Error
}

func (Permissions) GetIdsByCodes(codes []string) (lists []string, err error) {
	var model models.Permissions
	err = common.DB.Model(&model).Where("code in (?)", codes).Pluck("id", &lists).Error
	return
}
